
var config = require('./config.js')
var util = require('./util.js');


const Token = ""; 
const WxCode = "";


var doRequest = (url, param,method,login,token,callBack) => {
  util.showBusy('请求中...');
  var header = {
    "Content-Type": "application/x-www-form-urlencoded",
    

  };
 
  if(login == true){
    header = {
      "Content-Type": "application/json",
      "Accept":"application/json",
      // "WyxSoapHeader":token,
      'token':token,
    };
  }
  var options = {
    url: url,
    login: true,
    method:method,
    header:header,
    success: result => {
      wx.hideToast();
      console.log(result);
      var res = result.data
      if (res.code == -1) {
        console.log('重新登录');

      }else{
        callBack(res);
      }
    },
    fail: error => {
      util.showModel('请求失败', error);
    }
  }
  if(param != null){
    options.data = param;
  }
  wx.request(options);  
};



var addresUrls = [];

// 多图上传
var uploadimgs = (data, callBack) => {
  util.showBusy('上传中...');

  if(!data.i){
    var da = {};
    addresUrls = [];
    da.path = data;
    data = da;
  }
  
  var 
    i = data.i ? data.i : 0,//当前上传的哪张图片
    success = data.success ? data.success : 0,//上传成功的个数
    fail = data.fail ? data.fail : 0;//上传失败的个数
  

  wx.uploadFile({
    url: config.service.uploadUrl,
    filePath: data.path[i],
    name: 'file',//这里根据自己的实际情况改
    success: (resp) => {
      success++;//图片上传成功，图片上传成功的变量+1
      console.log('数组', addresUrls,resp);
      addresUrls = addresUrls.concat(JSON.parse(resp.data).data.imgUrl)
    },
    fail: (res) => {
      fail++;//图片上传失败，图片上传失败的变量+1
     
    },
    complete: () => {
      wx.hideToast();
      i++;//这个图片执行完上传后，开始上传下一张
      if (i == data.path.length) {   //当图片传完时，停止调用          
        
        callBack(addresUrls);
       
      } else {//若图片还没有传完，则继续调用函数

        data.i = i;
        data.success = success;
        data.fail = fail;
        uploadimgs(data,callBack);
      }

    }
  });
}

module.exports = { doRequest, uploadimgs ,Token};